package com.ruoyi.common.utils.ocr;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.config.RuoYiConfig;
import lombok.extern.slf4j.Slf4j;

import java.io.File;
import java.lang.reflect.Field;
import java.util.List;

@Slf4j
public class OcrUtils {
    public static List<OcrResultInfo> ocrJpg(File file) {
        String ocrUrl = RuoYiConfig.getOcrUrl();
        String body = HttpRequest.post(ocrUrl).timeout(1000*60*3).form("imageFile", file).execute().body();
        System.out.println(body);
        JSONObject bodyObj = JSONUtil.parseObj(body);
        Integer code = bodyObj.getInt("code");
        if (code == 0){
            JSONObject dataObj = bodyObj.getJSONObject("data");
            JSONArray result = dataObj.getJSONArray("result");
            List<OcrResultInfo> list = result.toList(OcrResultInfo.class);
            return list;
        }else {
            log.error(body);
            throw new RuntimeException("OCR识别接口访问异常");
        }
    }
    public static <T> T ocrResultInfo2Bean(OcrResultInfo ocrResultInfo , Class<T> clazz) {
        try {
            Field[] fields = clazz.getDeclaredFields();
            T entity = clazz.newInstance();
            for (Field field : fields) {
                OcrPoint annotation = field.getAnnotation(OcrPoint.class);
                if (annotation != null) {
                    double xPercent = annotation.xPercent();
                    double yPercent = annotation.yPercent();
                    int x = annotation.x();
                    int y = annotation.Y();
                    if (xPercent>0 && yPercent>0) {
                        List<OcrResultPoint> points = ocrResultInfo.getPoints();

                    }else if (x>0 && y>0) {

                    }
                }
            }
            return entity;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    private static boolean inScope(List<OcrResultPoint> points , OcrResultPoint point){
        double xPercent = point.getXPercent();
        double yPercent = point.getYPercent();
        OcrResultPoint p1 = points.get(0);
        OcrResultPoint p2 = points.get(1);
        OcrResultPoint p3 = points.get(2);
        OcrResultPoint p4 = points.get(3);
        if (xPercent>0 && yPercent>0) {
            if (xPercent>p1.getXPercent() && yPercent>p1.getYPercent()) {}
        }
        return false;
    }
}
